Dealing with scope in a recursive Python function